<?php
/**
 * SimplePie Aggregator for multiple RSS Feeds 
 */

/**
 * 
 */

/**
 * SimplePie Aggregator for multiple RSS Feeds
 *
 * @author Anthony Free
 */
class SimplePieAggregator {
    protected $initialised = false;
    protected $rss_classes = array();
    
    protected $items = array();
    protected $item_order = array();
    protected $hash_map = array();
    
    public function __construct(array $rssFeeds) {
	foreach($rssFeeds as $key => $value) {
	    $feed = new SimplePie();
	    $feed->set_feed_url($value);
	    $this->rss_classes[] = $feed;
	}
    }
    
    public function aggregate() {
	foreach($this->rss_classes as $key => $value) {
	    $value->init();
	    
	    // Generate a Unique HashMap Style Key for ordering the array
	    foreach($value->get_items() as $item) {
		$matched = false; $j = 0;
		// Generate the Keyname for the entry
		while($matched === false) {
		    $id = time() + rand(100000, 999999);
		    if(array_key_exists($id, $this->item_order) === true || $j > 9) {
			$matched = true;
			break;
		    }
		    $j++;
		}
		// Push into holding arrays
		$this->item_order[$id] = $item->get_date('U');
		$this->hash_map[$id] = $item;
	    }
	}
	// Associative Sort the items in reverse (descending order)
	arsort($this->item_order, SORT_NUMERIC);
	// Push sorted elements (in order) to the items array
	foreach($this->item_order as $key => $value) {
	    $this->items[] = $this->hash_map[$key];
	}
	$this->initialised = true;
    }
    
    public function &get_items() {
	if($this->initialised === false) {
	    $this->aggregate();
	}
	return $this->items;
    }
}

?>
